<?
/**
 * cache file wirter
 *
 */
class FileWriter {
  /**
   * 写文件
   *
   * @param unknown_type $fpath
   * @param unknown_type $buf
   * @param unknown_type $length
   * @return unknown
   */
  static public function f_xwrite($fpath, $buf, $length = -1) {
    $ret = 0;

    if ($length < 0) $length = strlen($buf);
    if ($length == 0) {
      @unlink($fpath);
      return 1;
    }

    $fd = @fopen($fpath, "r+");
    if (!$fd) $fd = @fopen($fpath, "w");
    if (!$fd) return $ret;

    flock($fd, LOCK_EX);
    fseek($fd, 0, SEEK_SET);
    if (fwrite($fd, $buf, $length)) {
      ftruncate($fd, $length);
      $ret = 1;
    }
    flock($fd, LOCK_UN);
    fclose($fd);

    # 权限设置为777
    chmod($fpath, 0777);
    return $ret;
  }

  /**
   * 创建目录
   *
   * @param unknown_type $fpath
   */
  static public function MakeDir($fpath) {
    if (!is_dir($fpath)) {
      mkdir($fpath, 0777);
    }
  }
}

?>